import os
import sys
import re
from config import *

version = sys.version_info.major

committed_list = []


def save_attachment(filename, filedata):
    save_path = get_save_path(filename)
    if echo:
        print('saving file: %s' % save_path)
    if not save_path:
        return
    if version == 2:
        fout = open(save_path, 'wr')
    else:
        fout = open(save_path, 'w')
    fout.write(filedata)


def get_save_path(filename):
    if not parse:
        return base_path + '/' + filename
    # parse filename
    m = re.match(student_id, filename)
    if not m:
        return None
    student = m.group(0)
    i = filename.find(course_name)
    if i == -1:
        return None
    j = i + course_name.__len__()
    course = filename[i:j]
    i = filename.find('-'+serial_id, i)
    if i == -1:
        return None
    j = i + serial_id.__len__() + 1
    serial = filename[i+1:j]
    i = filename.rfind('.')
    type_name = filename[i+1:]
    if echo:
        print('parsing: %s, %s, %s' % (student, course, serial))
    # update statistics
    committed_list.append(int(student[-3:]))
    # get save path
    save_file = student + '-' + course + '-' + serial + '.' + type_name
    save_dir = base_path + '/' + course + '/' + serial
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    save_path = save_dir + '/' + save_file
    return save_path


def check_base():
    if not os.path.exists(base_path):
        os.makedirs(base_path)
    os.chdir(base_path)


def count():
    print ('------count------')
    total_list = [i for i in range(lower, upper + 1)]
    for i in committed_list:
        total_list.remove(i)
    print('accepted count: %d' % committed_list.__len__())
    print('uncommitted count: %d' % total_list.__len__())
    print('total: %d' % (upper - lower + 1))


if __name__ == '__main__':
    pass
